package com.szqhyxj.youxiangju.biz.core;

import android.app.Activity;
import android.app.Application;
import android.app.DownloadManager;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;

import com.szqhyxj.youxiangju.BuildConfig;
import com.szqhyxj.youxiangju.BusinessLogicException;
import com.szqhyxj.youxiangju.NoLoginException;
import com.szqhyxj.youxiangju.biz.entrace.EntranceManager;
import com.szqhyxj.youxiangju.biz.login.LoginActivity;
import com.szqhyxj.youxiangju.biz.merchantHome.MerchantContainerActivity;
import com.szqhyxj.youxiangju.biz.push.service.PushUtil;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import org.xutils.x;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import io.reactivex.exceptions.OnErrorNotImplementedException;
import me.jessyan.autosize.AutoSizeConfig;

public class App extends Application {

    public static App app;

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        TokenManager.INSTANCE.init(this);
        EntranceManager.INSTANCE.init(this);
        initGlobeActivity();

        PushUtil.init(this);

        initGlobalException();

        UMConfigure.init(this, BuildConfig.UMENG_KEY, BuildConfig.CHANNEL, UMConfigure.DEVICE_TYPE_PHONE, "");

        //屏幕适配支持fragment
        AutoSizeConfig.getInstance().setCustomFragment(true);
        closeAndroidPDialog();//解决api兼容问题

        x.Ext.init(this);
        x.Ext.setDebug(true);

    }
    private void closeAndroidPDialog(){
//        android9.0 反射关闭讨厌的反射对话框
        if(android.os.Build.VERSION.SDK_INT<28){
            return;
        }
        try {
            Class aClass = Class.forName("android.content.pm.PackageParser$Package");
            Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
            declaredConstructor.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Class cls = Class.forName("android.app.ActivityThread");
            Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
            declaredMethod.setAccessible(true);
            Object activityThread = declaredMethod.invoke(null);
            Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
            mHiddenApiWarningShown.setAccessible(true);
            mHiddenApiWarningShown.setBoolean(activityThread, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void initGlobalException() {
        MobclickAgent.setCatchUncaughtExceptions(false);
        Thread.setDefaultUncaughtExceptionHandler((paramThread, paramThrowable) -> {
            if (paramThrowable instanceof NoLoginException) {
                toLogin();
            }
            if (paramThrowable instanceof BusinessLogicException) {
                Toast.makeText(topActivity, paramThrowable.getMessage(), Toast.LENGTH_SHORT).show();
            }
            if (paramThrowable instanceof OnErrorNotImplementedException) {
                if (paramThrowable.getCause() instanceof NoLoginException) {
                    toLogin();
                    return;
                }else if (paramThrowable.getCause() instanceof BusinessLogicException) {
                    Toast.makeText(topActivity, paramThrowable.getMessage(), Toast.LENGTH_SHORT).show();
                    return;
                }else if(topActivity instanceof MerchantContainerActivity && paramThrowable.getMessage().contains("版本")){ //拦截首页最新版本提示
                    return;
                }else {
                    //未知网络异常
                    Log.w("网络异常", "initGlobalException: "+paramThrowable.getMessage());
                    Toast.makeText(topActivity, "网络连接异常", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            MobclickAgent.reportError(getApplicationContext(), paramThrowable);
            Log.e("异常信息", inputErrorLog(paramThrowable));
        });
    }
    private void toLogin() {
        TokenManager.INSTANCE.clear();
        UserInfoManger.INSTANCE.clear();
        LoginActivity.start(topActivity);
    }

    private Activity topActivity;

    private void initGlobeActivity() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                topActivity = activity;
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                topActivity = activity;
            }

            @Override
            public void onActivityStarted(Activity activity) {
                topActivity = activity;
            }

            @Override
            public void onActivityResumed(Activity activity) {
                topActivity = activity;
            }

            @Override
            public void onActivityPaused(Activity activity) {
                topActivity = activity;
            }

            @Override
            public void onActivityStopped(Activity activity) {
                topActivity = activity;
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }
        });
    }

    public static App getApplication() {
        return app;
    }

    //异常信息打印
    public String inputErrorLog(Throwable paramThrowable) {
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        paramThrowable.printStackTrace(printWriter);
        Throwable cause = paramThrowable.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        StringBuffer sb = new StringBuffer();
        sb.append(result);
        return sb.toString();
    }

}